package com.heima.behavior.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    //注入mongodb 模板对象
    @Autowired
    MongoTemplate mongoTemplate;

    //注入行为实体查询
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 用户阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer uid = AppThreadLocalUtils.getUser().getId();
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(uid, dto.getEquipmentId());
        //3. 判断阅读行为是否存在
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        ApReadBehavior behavior = new ApReadBehavior();

        if (apReadBehavior == null) {
            // 不存在  创建阅读行为 并初始化count字段值为 1
            behavior.setEntryId(entry.getId());
            behavior.setArticleId(dto.getArticleId());
            behavior.setCount((short) 1);
            behavior.setCreatedTime(new Date());
            behavior.setUpdatedTime(new Date());
            mongoTemplate.insert(behavior);
        } else {
            //4. 存在  将阅读行为的count字段加1 并修改
            Query query1 = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
            Update update = new Update();
            update.set("count", apReadBehavior.getCount() + 1).set("updateTime", new Date());
            mongoTemplate.updateMulti(query1, update, ApReadBehavior.class);

        }

        //创建mess对象
        NewBehaviorDTO articleMess = new NewBehaviorDTO();
        //设置类型为阅读 views
        articleMess.setType(NewBehaviorDTO.UpdateArticleType.VIEWS);
        //设置文章id
        articleMess.setArticleId(dto.getArticleId());
        //判断是否点赞 点赞 add+1  取消点赞 add-1
        articleMess.setAdd(1);

        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE
                , JSON.toJSONString(articleMess));
        //点赞发送消息
        log.info("点赞行为发送消息 ===> {}", JSON.toJSONString(articleMess));
        return ResponseResult.okResult();
    }
}
